package com.solocredit.finance.ui.loan.act

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.os.Handler
import android.os.Looper
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.View
import com.solocredit.finance.R
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.base.utils.thread.TimingThread
import com.solocredit.finance.config.MullaConfigs
import com.solocredit.finance.databinding.ActMullaLoanApplyWaitBinding
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.mvp.ProAct
import com.solocredit.finance.utils.event.MullaEventData
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.helper.SharedHelper
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/5 18:45
 * @Annotation：申请贷款等待
 */
class MullaLoanApplyWaitAct: ProAct(), TimingThread.ITimingThreadListener {
    lateinit var binding: ActMullaLoanApplyWaitBinding
    private var timeThread: TimingThread? = null
    //等待时长
    private var countdown = 9

    companion object {
        private const val INTENT_KEY_PRODUCT = "product"
        private const val INTENT_KEY_TOKEN = "token"
        fun start(context: Context, pName: String, pToken: String) {
            val intent = Intent(context, MullaLoanApplyWaitAct::class.java)
            intent.putExtra(INTENT_KEY_PRODUCT, pName)
            intent.putExtra(INTENT_KEY_TOKEN, pToken)
            context.startActivity(intent)
        }
    }

    override fun getMullaRootView(): View {
        binding = ActMullaLoanApplyWaitBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initMullaView() {
        setMullaTitleBarColor(Color.parseColor("#FFFFFFFF"))
        setMullaTextTitle("")
        setMullaBackBtnVisibility(View.INVISIBLE)
        setMullaRightBtnRes(R.mipmap.mulla_loan_apply_wait_kefu)

        val textSMS = getString(R.string.loan_apply_wait_sms)
        val showText = String.format(getString(R.string.loan_apply_wait_tips),textSMS)

        val smsIndex = showText.indexOf(textSMS)
        val spString = SpannableString(showText)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFFF0000")), smsIndex, smsIndex + textSMS.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spString.setSpan(StyleSpan(Typeface.BOLD), smsIndex, smsIndex + textSMS.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        binding.textWaitTips.text = spString
    }

    override fun initMullaListener() {
        //联系客服
        rootViewBinding.ivFun.setOnClickListener {
            showMullaKefuDialog("Loan SMS Preview Page",loadProductName(),loadProductToken())
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_CUSTOMER, "Loan SMS Preview Page")
        }
    }

    override fun initMullaData() {
        startTimeThread()

        //牌照信息
        val licenseInfo = MullaCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.addView(licenseView())
            binding.licenseLayout.visibility = View.VISIBLE
        }
    }

    /**
     * 启动倒计时
     */
    private fun startTimeThread() {
        if (timeThread != null) {
            timeThread?.stopThread()
        }
        //随机 10秒 等待时长
        countdown = 9
        showMullaTipsText()
        if (timeThread == null) {
            timeThread = TimingThread()
            timeThread?.setThreadDelayMillis(1000)
            timeThread?.setLoadListener(this)
        }
        timeThread?.startThread()
    }

    override fun onLoading() {
        if (countdown <= 1){
            countdown = 9
            timeThread?.stopThread()
            showMullaLoading(isTOuchOut = false, isCancel = true)
            showMullaLoanApplySuccess()
            return
        }
        countdown--
        showMullaTipsText()
    }

    /**
     * 设置文本
     */
    @SuppressLint("SetTextI18n")
    private fun showMullaTipsText(){
        binding.textCountdown.text = "${countdown}s"
        showMullaStepStatusView()
    }

    /**
     * 贷款订单创建成功
     */
    private fun showMullaLoanApplySuccess(){
        Handler(Looper.getMainLooper()).postDelayed({
            //刷新主流程
            MyApp.app.publisher.publish(MullaEventData(MullaEventData.TYPE.MULLA_PROCESS_REFRESH))
        },500)
    }

    /**
     * 显示状态
     */
    private fun showMullaStepStatusView(){
        if (countdown in 7..9){
            binding.imgStep1.setImageResource(R.mipmap.mulla_wait_step2_icon)
            binding.vStep1Bottom.setBackgroundColor(Color.parseColor("#FFBBBBBB"))

            binding.vStep2Top.setBackgroundColor(Color.parseColor("#FFBBBBBB"))
            binding.imgStep2.setImageResource(R.mipmap.mulla_wait_step3_icon)
            binding.vStep2Bottom.setBackgroundColor(Color.parseColor("#FFBBBBBB"))

            binding.vStep3Top.setBackgroundColor(Color.parseColor("#FFBBBBBB"))
            binding.imgStep3.setImageResource(R.mipmap.mulla_wait_step3_icon)
            return
        }

        if (countdown in 4..6){
            binding.imgStep1.setImageResource(R.mipmap.mulla_wait_step1_icon)
            binding.vStep1Bottom.setBackgroundColor(Color.parseColor("#FF4DB673"))

            binding.vStep2Top.setBackgroundColor(Color.parseColor("#FF4DB673"))
            binding.imgStep2.setImageResource(R.mipmap.mulla_wait_step2_icon)
            binding.vStep2Bottom.setBackgroundColor(Color.parseColor("#FFBBBBBB"))

            binding.vStep3Top.setBackgroundColor(Color.parseColor("#FFBBBBBB"))
            binding.imgStep3.setImageResource(R.mipmap.mulla_wait_step3_icon)
            return
        }
        binding.imgStep1.setImageResource(R.mipmap.mulla_wait_step1_icon)
        binding.vStep1Bottom.setBackgroundColor(Color.parseColor("#FF4DB673"))

        binding.vStep2Top.setBackgroundColor(Color.parseColor("#FF4DB673"))
        binding.imgStep2.setImageResource(R.mipmap.mulla_wait_step1_icon)
        binding.vStep2Bottom.setBackgroundColor(Color.parseColor("#FF4DB673"))

        binding.vStep3Top.setBackgroundColor(Color.parseColor("#FF4DB673"))
        binding.imgStep3.setImageResource(R.mipmap.mulla_wait_step2_icon)
    }

    /**
     * 获取查看的产品名称
     */
    fun loadProductName(): String {
        return intent.extras?.getString(INTENT_KEY_PRODUCT).toString()
    }

    /**
     * 获取查看的产品Token
     */
    fun loadProductToken(): String {
        return intent.extras?.getString(INTENT_KEY_TOKEN).toString()
    }

    override fun onMullaEvent(event: MullaEventData) {
        super.onMullaEvent(event)
        if(event.eventType == MullaEventData.TYPE.MULLA_PROCESS_REFRESHED){//总流程刷新完成
            hideMullaLoading()
            val processStr = SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_PROCESS)
            if (processStr.isNotEmpty()){
                val processData = JSONObject(processStr)
                // TODO: 根据 smsFlag 或 whatsappFlag 判断是否需要校验手机号
                val smsFlag = processData.optString("smsFlag") == "YES"
                val whatsappFlag = processData.optString("whatsappFlag") == "YES"
                if (!smsFlag && !whatsappFlag){
                    //不需要校验手机号 - 进入贷款详情
                    val pLogo = MullaConfigs.clickProductLogo
                    val pName = MullaConfigs.clickProductName
                    val pToken = MullaConfigs.clickProductToken
                    val pTitle = MullaConfigs.clickProductTitle
                    MullaLoanDetailsAct.start(this, pLogo, pName, pToken,pTitle)
                }
                finish()
            }
        }
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_LOAN_SMS_PREVIEW_START, "")
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_LOAN_SMS_PREVIEW_END, "")
        if (timeThread != null) {
            timeThread?.stopThread()
            timeThread = null
        }
    }
}